<template>
  <div class="comment-post">
    <van-field
      class="post-field"
      v-model.trim="message"
      rows="2"
      autosize
      type="textarea"
      maxlength="50"
      placeholder="请输入留言"
      show-word-limit
    />
    <van-button class="post-btn" @click="onPost" :disabled="!message.length"
      >发布</van-button
    >
  </div>
</template>

<script>
import { addComment } from '@/api/comment'
export default {
  name: 'CommentPost',
  components: {},
  inject: {
    // 这个地方是接受爷爷组件所传递的文章id
    articleId: {
      type: [String, Object, Number],
      default: null
    }
  },
  props: {
    target: {
      type: [String, Object, Number],
      required: true
    }
  },
  data() {
    return {
      message: ''
    }
  },
  computed: {},
  watch: {},
  created() {},
  mounted() {},
  methods: {
    // 点击发布把要发布的评论提交到数据库里面
    async onPost() {
      try {
        const { data } = await addComment({
          target: this.target.toString(), // 文章评论里面的id是大数字所以这个地方要转成字符串
          content: this.message,
          // 当在文章发表评论的时候就传入null,当要给评论进行评论的时候,就传入文章id
          art_id: this.target === this.articleId ? null : this.articleId
        })
        // 把评论完之后的返回回来的数据列表,返回给父组件index
        this.$emit('commentSuccess', data.data)
        // 然后清空列表
        this.message = ''
      } catch (err) {
        this.$toast.fail('添加失败')
      }
    }
  }
}
</script>

<style scoped lang="less">
.comment-post {
  display: flex;
  align-items: center;
  padding: 32px 0 32px 32px;
  .post-field {
    background-color: #f5f7f9;
  }
  .post-btn {
    width: 150px;
    border: none;
    padding: 0;
    color: #6ba3d8;
    &::before {
      display: none;
    }
  }
}
</style>
